#!/usr/bin/python

"""
Copyright (c) 2013 Eric Chai <electromatter@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

"""
TODO: watch scheduleing, notification, watch multiple tumblrs,
      add more to filename dictionary, be more vorbose, error handling,
      other media(ex video, text, sounds), perfered width setting,
      Target directory string builder, paralellization, rate limiting
"""
import urllib2 as URL
import xml.etree.ElementTree as ET
import sys
import getopt
import os
from collections import Counter

class Done(Exception): pass
class Args(Exception): pass

global level
level = 0

def vorbose(lev, *args):
    if lev <= level:
        if lev > 0:
            print >> sys.stderr, lev,
        for arg in args:
            print >> sys.stderr, arg,
        print >> sys.stderr
        sys.stderr.flush()

def download(url, target):
    request = URL.urlopen(url)
    
    f = open(target, 'w')
    
    while True:
        c = request.read(65536)
        if not c:
            break
        f.write(c)
    
    f.close()

def fetch(tumblr, target, tags=[], filename='%(filename)s', rescan=False):
    tagstr = ''
    
    count = 0
    
    for tag in tags:
        tagstr += 'tagged=' + tag + '&'

    try:
        start = 0
        num = 50
        while True:
            url = 'http://' + tumblr + '.tumblr.com/api/read/?' + tagstr + 'type=photo&num=' + str(num) + '&start=' + str(start)
            
            vorbose(4, 'checking url: ', url)

            request = URL.Request(url, headers={"Accept" : "application/xml"})

            u = URL.urlopen(request)

            tree = ET.parse(u)

            poststree = tree.find("posts")

            poststree.get("total")

            posts = poststree.findall("post")
            
            if not posts:
                break
                
            vorbose(4, 'found', len(posts), 'post(s)')
                
            for post in posts:
                miptree = post.findall("photo-url")
                mips = {}
                for mip in miptree:
                    mips[mip.get("max-width")] = mip.text
                width = max(mips, key=int)
                url = mips[width]

                src = url.rsplit('/',1)[1]
                sp = src.rsplit('.',1)
                name = filename % dict(filename=src, name=sp[0], ext=sp[1], width=width)
                
                path = os.path.join(target, name)
                
                if os.path.exists(path):
                    if not rescan:
                        raise Done
                    else:
                        continue
                
                vorbose(1, 'downloading:', name)
                vorbose(2, 'from:', url)
                vorbose(4, 'full path:', path)
                
                download(url, path)
                count += 1
            start += num
    except Done:
        return count
    return count

def main(argv):
    global level
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:],"hvst:n:w:")
        count = Counter(opts)
        level = count[('-v', '')]
        opt = dict(opts)
        if '-h' in opt:
            raise Args
        if len(args) != 2:
            raise Args
        tumblr = args[0]
        target = args[1]
        tags = []
        for arg in opts:
            if arg[0] == '-t':
                tags.insert(len(tags), arg[1])
        filename = '%(filename)s'
        if '-n' in opt:
            filename = opt['-n']
        rescan = '-s' in opt
    except (getopt.GetoptError, Args):
        vorbose(0, 'usage: ./' + os.path.basename(__file__), '[options] <tumblr username> <target directory>...')
        vorbose(0, 'Options:')
        vorbose(0, '\t-n <format>\ttarget file name format, default: $(filename)s')
        vorbose(0, '\t\tformat variables:')#filename=src, name=sp[0], ext=sp[1], width=width
        vorbose(0, '\t\t$(filename)s - source filename')
        vorbose(0, '\t\t$(name)s - source filename\'s name')
        vorbose(0, '\t\t$(ext)s - source filename\'s extension')
        vorbose(0, '\t\t$(width)s - file width')
        vorbose(0, '\t-t <tag>\tfilter for only this tag. multiple tags may be included')
        vorbose(0, '\t-s\t\trescans and redownload any missing files')
        vorbose(0, '\t-v\t\tvorbose level (max -vvvv)')
        vorbose(0, '\t-h\t\tprint this help message')
        sys.exit(2)
    
    if not os.path.exists(target):
        vorbose(1, 'target path does not exist, createing:\n\t', target)
        os.makedirs(target)
    
    vorbose(2, 'watching:', tumblr, 'to:', target, 'tags:', tags, 'filename:', filename)
    vorbose(0, 'fetching', tumblr + '...')
    
    fetched = fetch(tumblr, target, tags=tags, filename=filename, rescan=rescan)
    
    if fetched == 0:
        vorbose(0, tumblr, 'Up-to-date')
    else:
        vorbose(0, tumblr, 'fetched:',fetched)

if __name__ == "__main__":
    main(sys.argv[1:])
